<template>
  <div class="login-main relative">
    <!--oem-->
    <!-- <div class="oem-container flex-x-start-center">
      <img :src="'/static/oem/'+oemMap.activeOem+'/logo.png'" class="logo" alt>
      <h1 class="brand">服务商后台</h1>
    </div> -->
    <div class="bgPic"><img src="../../../public/static/img/login-img/bg.png" alt=""></div>
    <div class="logo_bg"><img src="../../../public/static/img/login-img/logo.png" alt=""></div>
    <div class="draw"><img src="../../../public/static/img/login-img/draw.png" alt=""></div>
    <div class="welcomeTxt">
      <h2>Hi,</h2>
      <h2>欢迎登录服务商后台</h2>
    </div>
    <!-- login-->
    <div class="login-container">
      <ul class="tab-nav flex-x-between-center pointer" @click.stop="tabClick">
        <li :class="{ 'tab-item_active': activeTabName === 'form' }" data-tab="form" class="tab-item">
          账户登录
          <span v-if="activeTabName === 'form'" class="tab_underline" />
        </li>
        <li :class="{ 'tab-item_active': activeTabName === 'scan' }" data-tab="scan" class="tab-item">
          扫码登录
          <span v-if="activeTabName === 'scan'" class="tab_underline" />
        </li>
        <!-- <li v-show="activeTabName === 'form'" :class="{ 'tab-item_active': activeTabName === 'form' }" data-tab="form" class="tab-item">账户登录</li>
        <li v-show="activeTabName === 'scan'" :class="{ 'tab-item_active': activeTabName === 'scan' }" data-tab="scan" class="tab-item">扫码登录</li> -->

        <!-- <li v-show="activeTabName === 'scan'" data-tab="form" class="tab-item flex-x-end-center">
          <span data-tab="form">账户登录</span>
          <img src="@/assets/icon/i-user.png" data-tab="form" alt="" class="i-tab">
        </li>
        <li v-show="activeTabName === 'form'" data-tab="scan" class="tab-item flex-x-end-center">
          <span data-tab="scan">扫码登录</span>
          <img src="@/assets/icon/i-scan.png" data-tab="scan" alt="" class="i-tab">
        </li> -->
      </ul>
      <div class="content-container">
        <div v-show="activeTabName === 'form'" class="form-box flex-y-center">
          <el-form ref="form" :model="form" :rules="rules">
            <!-- <div class="label">账号</div> -->
            <el-form-item prop="username"><el-input v-model.trim="form.username" placeholder="账号/用户名" maxlength="50" @keyup.enter.native="login" /></el-form-item>
            <!-- <div class="label">密码</div> -->
            <el-form-item prop="password">
              <el-input v-model.trim="form.password" type="password" placeholder="请输入密码" maxlength="50" @keyup.enter.native="login" />
            </el-form-item>
            <!-- <div class="label">编号</div> -->
            <el-form-item prop="serialNo">
              <el-input v-model.trim="form.serialNo" placeholder="请输入编号" maxlength="10" @keyup.enter.native="login">
                <el-button
                  slot="suffix"
                  style="padding-right:5px; color: #FFB72F; font-size: 0.8vw; font-weight: 500;"
                  size="small"
                  type="text"
                  @click="handleFindSerial"
                >
                  忘记编号
                </el-button>
              </el-input>
            </el-form-item>
            <el-form-item v-if="form.isShow" class="roleAliasClass" prop="roleAlias">
              <el-radio-group v-model="form.isAdmin" placeholder="请选择登录角色">
                <el-radio label="false">机构</el-radio>
                <el-radio label="true">代理</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--<div class="flex-x-end-center">-->
            <!--  <el-checkbox v-model="rememberSerialNo" size="small" @change="rememberSerialNoChange">记住编号</el-checkbox>-->
            <!--</div>-->
          </el-form>
          <el-button type="primary" :loading="loading" round class="btn-login" @click.native.prevent="login">登录</el-button>
        </div>
        <div v-show="activeTabName === 'scan'" v-loading="qrcodeLoading" class="scan-box flex-y-center">
          <div class="qr-code-container  flex-y-center-center">
            <img class="qrcode_logo" src="../../../public/static/img/login-img/qrcode_logo.png" alt="">
            <vue-qr v-if="qrcodeUrl" :text="qrcodeUrl" :margin="10" class="qr-code-img" />
            <div v-if="isQrcodeExpire" class="refresh-mask" @click="getLoginQrcode">
              <p>
                二维码已失效
                <br>
                点击刷新
              </p>
            </div>
          </div>
          <div class="login-tips">打开微信扫一扫</div>
        </div>
      </div>
    </div>

    <!--公众号-->
    <!--    <div class="public-container flex-y-center-center">-->
    <!--      <img src="@/assets/oem/default/logo_1.png" alt="" class="qr-code">-->
    <!--      <div>酷点公众号，扫码关注</div>-->
    <!--    </div>-->

    <!--找回编号-->
    <FindSerialDialog ref="findSerialDialog" />
  </div>
</template>

<script>
import FindSerialDialog from './components/FindSerialDialog'
import { mapGetters } from 'vuex'
import { setToken, removeToken } from '@/utils/auth'
import { loginQrcode, loginQrcodeState } from '@/api/user/auth'

export default {
  components: {
    FindSerialDialog
  },
  data() {
    // 校验方法
    // const validateUsername = (rule, value, callback) => {
    //   if (this.$isNull(value)) {
    //     callback(new Error('请输入用户名'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validatePassword = (rule, value, callback) => {
    //   if (this.$isNull(value)) {
    //     callback(new Error('请输入密码'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      // 配置
      // 校验字段
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
        password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }],
        serialNo: [{ required: true, message: '请输入编号', trigger: ['blur', 'change'] }]
      },
      // 状态
      loading: false,
      qrcodeLoading: false,
      isQrcodeExpire: false,
      isStopCheckQrcodeState: true,
      // 数据
      activeTabName: 'form',
      scope: 1,
      qrcodeNo: null,
      qrcodeUrl: null,
      // rememberSerialNo: JSON.parse(sessionStorage.getItem('Servicer-Remember-SerialNo')) || false,
      rememberSerialNo: true,
      form: {
        username: null,
        password: null,
        isAdmin: null,
        isShow: false,
        serialNo: sessionStorage.getItem('Servicer-SerialNo')
      }
    }
  },
  computed: {
    ...mapGetters(['oemMap', 'userInfo'])
  },
  watch: {},
  beforeCreate() {},
  created() {
    // removeToken()
    // 设置流量预警开关是否打开
    localStorage.setItem('flowWarnTag', 'open')
  },
  beforeMount() {},
  mounted() {
    setTimeout(() => {
      this.getParamResults()
    }, 2000)
  },
  beforeUpdate() {},
  update() {},
  activated() {},
  deactivated() {},
  beforeDestroy() {
    this.isStopCheckQrcodeState = true
  },
  destroyed() {},
  methods: {
    /**
		 * 数据组
		 */
    // 获取登陆二维码
    getLoginQrcode() {
      this.isStopCheckQrcodeState = false
      this.isQrcodeExpire = false
      this.qrcodeLoading = true
      loginQrcode({ data: { qrcodeType: 0, scope: this.scope } })
        .then(res => {
          this.qrcodeNo = res.data.qrcodeNo
          this.qrcodeUrl = res.data.qrcodeContent
          this.isQrcodeExpire = false
          this.checkQrcodeState()
        })
        .finally(() => {
          this.qrcodeLoading = false
        })
    },

    // 检查微信登陆二维码状态
    checkQrcodeState() {
      if (!this.qrcodeNo) return
      const params = {}
      params.qrcodeNo = this.qrcodeNo
      loginQrcodeState({ params: params })
        .then(res => {
          switch (res.data.qrcodeStatus) {
            case 0:
            case 1: {
              //  qrcodeStatus  -1: 二维码已失效, 0: 未扫码, 1:已扫码
              //  loginStatus  0: 未登录, 1:已登陆
              if (res.data.loginStatus === 0) {
                const timerId = setTimeout(() => {
                  if (this.isStopCheckQrcodeState) return clearTimeout(timerId)
                  this.checkQrcodeState()
                }, 2000)
              } else if (res.data.loginStatus === 1 && res.data.loginResult) {
                setToken(res.data.loginResult.token)
                debugger
                this.$store.state.user.token = res.data.loginResult.token
                this.$router.push({ path: '/' })
              }
              break
            }
            default:
              // -1 失效
              this.isQrcodeExpire = true
              this.isStopCheckQrcodeState = true
              break
          }
        })
        .catch(() => {
          this.isQrcodeExpire = true
          this.isStopCheckQrcodeState = true
        })
        .finally(() => {})
    },

    /**
		 * 按钮组
		 */
    // login
    login() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          setTimeout(() => {
            if (sessionStorage.getItem('exist_many_account') === 'exist_many_account') {
              this.form.isShow = true
            } else {
              this.form.isShow = false
            }
            sessionStorage.removeItem('exist_many_account')
          }, 1000)

          if (this.rememberSerialNo) {
            sessionStorage.setItem('Servicer-SerialNo', this.form.serialNo)
          } else {
            sessionStorage.removeItem('Servicer-SerialNo')
          }
          this.$store
            .dispatch('user/Login', this.form)
            .then(() => {
              this.$router.push({
                path: '/'
              })
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // tab
    tabClick(e) {
      if (!e.target.dataset.tab) return
      this.activeTabName = e.target.dataset.tab
      this.isStopCheckQrcodeState = true
      this.isQrcodeExpire = false
      this.activeTabName === 'scan' && this.getLoginQrcode()
    },

    // 忘记编号
    handleFindSerial() {
      this.$refs.findSerialDialog.open().then(res => {
        this.form = JSON.parse(res)
        this.$nextTick(() => {
          this.login()
        })
      })
    },
    /**
		 * 状态组
		 */
    // SerialNoChange
    rememberSerialNoChange(val) {
      sessionStorage.setItem('Servicer-Remember-SerialNo', val)
    },
    /**
		 * 方法组
		 */

    /* 截取url参数 */
    getParamQueryString(url, name) {
      const subStr = name + '='
      if (url.indexOf(subStr) !== -1) {
        const arr = url.split(subStr)
        const sub1 = arr[1]
        if (sub1.indexOf('&') !== -1) {
          const arr2 = sub1.split('&')
          const sub2 = arr2[0]
          return sub2
        } else {
          return sub1
        }
      }
      return ''
    },
    /* 截取url参数结果 */
    getParamResults() {
      // 免登陆跳转
      // const url = window.location.href
      // console.log('url', url)
      // const paramList = ['headerName', 'token']
      // const getParam = []
      // paramList.forEach(el => {
      //   getParam.push(this.getParamQueryString(url, el))
      // })
      // console.log('截取-token', getParam[1])
      // setToken(getParam[1])
      // // setToken(res.data.loginResult.token)
      // this.$store.state.user.token = getParam[1]
      // this.$router.push({ path: '/' })

      // const href = window.location.href
      // if (href.indexOf('?') !== -1) {
      //   const arr = href.substring(href.lastIndexOf('?') + 1, href.length).split('&')
      //   arr[arr.length - 1] = arr[arr.length - 1].substring(0, arr[arr.length - 1].lastIndexOf('#'))
      //   const obj = {}
      //   arr.forEach(item => {
      //     const arrKey = item.split('=')
      //     obj[arrKey[0]] = arrKey[1]
      //   })
      //   const token = obj.token
      //   if (token) {
      //     removeToken()
      //     setToken(token)
      //     this.$store.commit('SET_TOKEN', token)
      //     this.$store.state.user.token = token
      //     // 重新获取当前路由,避免退出登录后,刷新被重新登陆
      //     // const path = this.$route.path
      //     // this.$router.push(path)
      //     window.location.href = this.$route.path
      //   }
      // }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/*main*/
.login-main {
	height: 100vh;
	background-color: #fff;
	overflow: hidden;
	position: relative;
	.bgPic {
		width: 100%;
		height: 100%;
		position: fixed;
		// z-index: 1;
		img {
			width: 100%;
			height: 100%;
		}
	}
	.logo_bg {
		width: 5%;
		position: fixed;
		top: 20%;
		left: 17%;
		img {
			width: 100%;
			height: 100%;
		}
	}
	.draw {
		width: 45%;
		position: fixed;
		bottom: 10%;
		left: 0;
		img {
			width: 100%;
			height: 100%;
		}
	}
	.welcomeTxt {
		position: fixed;
		top: 20vh;
		left: 23.5%;
		z-index: 1;

		h2 {
			font-weight: 500;
			font-size: 2vw;
			margin: 0;
			margin-bottom: 1vh;
		}
	}
}

/*oem*/
.oem-container {
	position: absolute;
	top: 40px;
	left: 40px;
	//margin: 40px 0 0 40px;

	.logo {
		width: 40px;
		height: 40px;
	}

	.brand {
		display: inline-block;
		margin-left: 20px;
		font-size: 20px;
		font-weight: bold;
		color: $primary;
	}
}

/*login*/
.login-container {
	position: absolute;
	top: 45%;
	right: 5%;
	width: 25%;
	margin-top: 6%;
	padding: 6vh 4vw;
	box-shadow: 0 5px 38px 0 #fcebd4;
	border-radius: 36px;
	transform: translate(-50%, -50%);
	background-color: white;
}

/*tab*/
.tab-nav {
	width: 100%;
	height: 4vh;

	.tab-item {
		width: 50%;
		height: 100%;
		// line-height: 50px;
		text-align: center;
		position: relative;
		font-size: 1vw;
		font-weight: bold;
		color: #b3b3b3;

		.tab_underline {
			width: 2vw;
			height: 0.5vh;
			background-color: #ffb72f;
			position: absolute;
			bottom: 0;
			left: 38%;
			border-radius: 20px;
		}

		.i-tab {
			width: 18px;
			height: 18px;
			margin-left: 8px;
		}

		&:nth-child(3),
		&:nth-child(4) {
			text-align: right;
		}
	}

	.tab-item_active {
		color: #ffb72f;
	}
}

/*content*/
.content-container {
	/*form*/
	.form-box {
		.label {
			height: 30px;
			line-height: 30px;
			color: #606266;
		}

		::v-deep {
			.el-form {
				width: 100%;
			}

			.el-form-item {
				margin-top: 7vh;
				margin-bottom: 0;
				::-webkit-input-placeholder {
					font-size: 0.8vw;
				}
			}
			.roleAliasClass {
				margin-top: 3vh;
			}

			.el-input {
				border-bottom: 1px solid #c0c4cc;
				background-color: white;
			}

			.el-input__inner {
				padding: 0;
				border: none;
				background-color: white;
				height: 5vh;
			}
		}

		.btn-login {
			margin-top: 25%;
			width: 100%;
			padding: 1.8vh 0;
			font-size: 1vw;
			background-color: #ffb72f;
			border: none;
		}
	}

	/*扫码盒子*/
	.scan-box {
		.qr-code-container {
			position: relative;
			width: 80%;
			height: 80%;
			margin: 10% 0 5%;

			.qr-code-img {
				width: 100%;
				height: 100%;
				// box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			}

			.qrcode_logo {
				position: absolute;
				top: 40%;
				left: 40%;
				width: 20%;
				height: 20%;
				background-color: white;
				border-radius: 10px;
			}
		}

		.refresh-mask {
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			line-height: 30px;
			background: #000;
			opacity: 0.8;
			color: #fff;
			text-align: center;
			cursor: pointer;
		}

		.login-tips {
			font-size: 16px;
		}
	}
}

/*公众号*/
.public-container {
	position: absolute;
	right: 80px;
	bottom: 130px;
	width: 200px;
	height: 200px;
	background-color: #f7f7f7;
	border-radius: 10px;

	.qr-code {
		margin-bottom: 20px;
		width: 110px;
		height: 110px;
	}
}
</style>
